package com.gao.mq.util;

import com.alibaba.fastjson.util.IOUtils;
import com.sun.xml.internal.messaging.saaj.util.ByteOutputStream;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import sun.nio.ch.IOUtil;

import javax.mail.Session;
import javax.mail.internet.MimeMessage;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

/**
 * 邮件工具类
 */
@Component
public class EmailUtil {

    @Value("${spring.mail.host}")
    private String host;
    @Value("${spring.mail.username}")
    private String from;
    @Value("${spring.mail.password}")
    private String password;

    /**
     * @param tos           发送人
     * @param subject       邮件主题
     * @param emailContent  邮件内容
     * @param isHtml        是否为HTML格式
     * @param attachments   附件
     * @throws Exception
     */
    public void send(Set<String> tos, String subject, String emailContent, boolean isHtml,
                     Map<String, InputStream> attachments) throws Exception {

        generalSend(host, password, from, tos, subject, emailContent, isHtml, attachments);
    }


    private void generalSend(String host, String password, String from, Set<String> tos, String subject,
                             String emailContent, boolean isHtml,
                             Map<String, InputStream> attachments) throws Exception {
        JavaMailSenderImpl senderImpl = new JavaMailSenderImpl();
        //设定mail server
        senderImpl.setHost(host);

        //建立邮件消息,发送简单邮件和html邮件的区别
        MimeMessage mailMessage = senderImpl.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(mailMessage, 1, "UTF-8");
        //设置寄件人
        messageHelper.setFrom(from);
        //设置收件人
        messageHelper.setTo(tos.toArray(new String[]{}));
        // 设置邮件主题
        messageHelper.setSubject(subject);
        //true 表示启动HTML格式的邮件
        messageHelper.setText(emailContent, isHtml);
        //添加文件文件
        if (attachments != null && attachments.size() > 0) {
            for (String fileName : attachments.keySet()) {
                InputStream in = attachments.get(fileName);
                ByteArrayResource bar = new ByteArrayResource(getBytes(in));
                messageHelper.addAttachment(fileName, bar);
            }
        }
        //设置邮箱属性
        Properties prop = new Properties();
        // 将这个参数设为true，让服务器进行认证,认证用户名和密码是否正确
        prop.put("mail.smtp.auth", "true");
        prop.put("mail.smtp.starttls.enable", "true");
        prop.put("mail.smtp.host", host);
        prop.put("mail.smtp.user", from);
        prop.put("mail.smtp.pass", password);
        //配置发送类信息
        senderImpl.setJavaMailProperties(prop);
        senderImpl.setUsername(from);
        senderImpl.setPassword(password);
        senderImpl.setSession(Session.getDefaultInstance(senderImpl.getJavaMailProperties()));
        //发送邮件
        senderImpl.send(mailMessage);
    }

    public static final int BUFFER_SIZE = 1024;
    /**
     *  InputStream 转 byte[]
     */
    public byte[] getBytes(InputStream in) throws IOException {
        ByteOutputStream bos = new ByteOutputStream();
        byte[] b = new byte[BUFFER_SIZE];
        int len = 0;
        while ((len = in.read(b, 0 , BUFFER_SIZE)) != -1) {
            bos.write(b, 0, len);
        }
        bos.flush();
        return bos.getBytes();
    }
}
